import path from 'node:path'
import { createDefineMock } from 'vite-plugin-mock-dev-server'
import { MockHttpItem } from 'vite-plugin-mock-dev-server/dist'

const SUCCESS = 200100
const ERROR400 = 400100
const ERROR401 = 401100
const ERROR403 = 403100
const ERROR404 = 404100
const ERROR500 = 500100

//@ts-ignore
//公共前缀，mock接口的路径需要与server访问的路径一致
const BASE_URL = import.meta.env.VITE_BASE_API

/**
 * 没有对body进行任何处理，需要手动设置完整的body结构
 */
const defineApiMock = createDefineMock((mock) => {
  // 预处理 mock url
  mock.url = path.join(BASE_URL, mock.url)
})

/**
 * 设置了body中请求成功时的默认数据结构
 */
const defineSuccessMock = createDefineMock((mock) => {
  // 预处理 mock url
  mock.url = path.join(BASE_URL, mock.url)
  //断言是MockHttpItem接口的实例
  mock = mock as MockHttpItem
  mock.body = { code: SUCCESS, data: mock.body, message: 'OK' }
})
/**
 * 设置了body中请求错误时的默认数据结构
 */
const defineError400Mock = createDefineMock((mock) => {
  // 预处理 mock url
  mock.url = path.join(BASE_URL, mock.url)
  //断言是MockHttpItem接口的实例
  mock = mock as MockHttpItem
  mock.body = { code: ERROR400, data: mock.body, message: 'BAD_REQUEST' }
})
const defineError401Mock = createDefineMock((mock) => {
  // 预处理 mock url
  mock.url = path.join(BASE_URL, mock.url)
  //断言是MockHttpItem接口的实例
  mock = mock as MockHttpItem
  mock.body = { code: ERROR401, data: mock.body, message: 'UNAUTHORIZED' }
})
const defineError403Mock = createDefineMock((mock) => {
  //@ts-ignore
  //自动给请求路径加前缀，mock接口的路径与axios请求时填入的路径一致即可自动代理
  mock.url = path.join(import.meta.env.VITE_BASE_API, mock.url)
  //断言是MockHttpItem接口的实例
  mock = mock as MockHttpItem
  mock.body = { code: ERROR403, data: mock.body, message: 'FORBIDDEN' }
})
const defineError404Mock = createDefineMock((mock) => {
  // 预处理 mock url
  mock.url = path.join(BASE_URL, mock.url)
  //断言是MockHttpItem接口的实例
  mock = mock as MockHttpItem
  mock.body = { code: ERROR404, data: mock.body, message: 'NOT_FOUND' }
})
const defineError500Mock = createDefineMock((mock) => {
  // 预处理 mock url
  mock.url = path.join(BASE_URL, mock.url)
  //断言是MockHttpItem接口的实例
  mock = mock as MockHttpItem
  mock.body = { code: ERROR500, data: mock.body, message: 'INTERNAL_SERVER_ERROR' }
})

export {
  defineApiMock,
  defineSuccessMock,
  defineError400Mock,
  defineError401Mock,
  defineError403Mock,
  defineError404Mock,
  defineError500Mock
}